import os
import subprocess
import shutil
import requests
import json
from dotenv import load_dotenv

# 加载 .env 文件
load_dotenv()

# 读取配置文件
def get_config():
    config = {
        "USER_AGENT": os.getenv("USER_AGENT"),
        "CONTENT_TYPE": os.getenv("CONTENT_TYPE"),
        "COOKIE": os.getenv("COOKIE"),
        "NAMESPACE_ID": os.getenv("NAMESPACE_ID"),
        "TARGET_ORG_ID": os.getenv("TARGET_ORG_ID"),
        "USERNAME_GITEE": os.getenv("USERNAME_GITEE"),
        "TOKEN_GITEE": os.getenv("TOKEN_GITEE"),
        "USERNAME_ATOMGIT": os.getenv("USERNAME_ATOMGIT"),
        "TOKEN_ATOMGIT": os.getenv("TOKEN_ATOMGIT")
    }
    return config

# 读取source.txt中的仓库地址
def read_source_file(filename):
    if not os.path.exists(filename):
        return None
    with open(filename, 'r') as file:
        repo_urls = file.read().strip().splitlines()
    return repo_urls

# 克隆仓库
def clone_repo(repo_url):
    repo_name = repo_url.split('/')[-1].replace('.git', '')
    clone_repos_path = 'clone_repos'
    
    # 检查并创建clone_repos目录
    if not os.path.exists(clone_repos_path):
        os.makedirs(clone_repos_path)
    
    # 目标路径
    target_path = os.path.join(clone_repos_path, repo_name)
    
    # 检查本地是否已经存在仓库目录
    if os.path.exists(target_path):
        shutil.rmtree(target_path)
    
    subprocess.run(['git', 'clone', repo_url, target_path], check=True)
    return target_path

# 在atomgit.com上创建新的仓库
def create_repo_on_b(repo_name, config):
    url = 'https://atomgit.com/api/v3/projects?_input_charset=utf-8'
    headers = {
        "User-Agent": config["USER_AGENT"],
        "Content-Type": config["CONTENT_TYPE"],
        "Cookie": config["COOKIE"]
    }
    payload = {
        # 拟创建的仓库名，可以是中文
        "name": repo_name,
        # 拟创建的仓库Code，会体现在 URL 中
        "path": repo_name,
        # 私有或者公开仓库，0 私有、1 公开
        "visibility_level": 0,
        # 组织或者用户的id
        "namespace_id": config['NAMESPACE_ID'],
        # 保持false默认
        "init_standard_service": False,
        # 保持默认
        "open_department_id_paths": [],
        # 组织或者用户的id
        "target_org_id": config['TARGET_ORG_ID']
    }
    response = requests.post(url, headers=headers, data=json.dumps(payload))
    if response.status_code == 201:
        repo_data = response.json()
        return repo_data['ssh_url_to_repo'], repo_data['http_url_to_repo']
    else:
        return None, None

# 检查是否能通过 SSH 连接
def can_connect_via_ssh():
    try:
        subprocess.run(['ssh', '-T', 'git@atomgit.com'], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        return True
    except subprocess.CalledProcessError:
        return False

# 将本地仓库推送到atomgit.com
def push_repo_to_b(local_repo_path, ssh_url, https_url, config):
    commands = [f'cd {local_repo_path}']
    
    # 删除已有的 remote origin
    commands.append('git remote remove origin || true')
    
    if can_connect_via_ssh():
        commands.append(f'git remote add origin {ssh_url}')
    else:
        commands.append(f'git remote add origin {https_url}')
        username = config['USERNAME_ATOMGIT']
        token = config['TOKEN_ATOMGIT']
        credentials_path = os.path.join(local_repo_path, '.git-credentials')
        with open(credentials_path, 'w') as cred_file:
            cred_file.write(f'https://{username}:{token}@atomgit.com\n')
        commands.append(f'git config --local credential.helper "store --file={credentials_path}"')

    # 将 main 分支重命名为 master
    commands.append('git branch -M master')
    
    commands.append('git push origin master')
    full_command = ' && '.join(commands)
    subprocess.run(full_command, shell=True, check=True)

# 主要处理逻辑
def main():
    config = get_config()
    source_file = 'source.txt'
    repo_urls = read_source_file(source_file)
    if repo_urls is None:
        return

    for repo_url in repo_urls:
        repo_name = clone_repo(repo_url)
        if not repo_name:
            continue
        ssh_url, https_url = create_repo_on_b(repo_name, config)
        if not ssh_url or not https_url:
            continue
        push_repo_to_b(repo_name, ssh_url, https_url, config)

if __name__ == '__main__':
    main()
